/**
 * Copyright (C) 2012  TopicBankEx
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.openingedu.mba.screen.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lurencun.android.support.v2.widget.ViewPager;
import com.lurencun.android.support.v2.widget.ViewPagerAdapter;
import com.openingedu.mba.R;
import com.openingedu.mba.common.AppSetting;
import com.openingedu.mba.entity.QuestionOptionVO;
import com.openingedu.mba.entity.QuestionVO;
import com.openingedu.mba.util.PracticeHandler;

/**
 * 
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-3-7
 */
public class CommonPracticeAdapter extends ViewPagerAdapter<QuestionVO> {

	private Vibrator mVirator;
	private final Context mContext;
	private PracticeHandler mHandler;
	
	/** 是否显示 **/
	private boolean showSolution = true;
	
	public CommonPracticeAdapter(Context context) {
		super(context);
		mContext = context;
		mVirator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
	}

	

	/* (non-Javadoc)
	 * @see com.lurencun.android.support.v2.widget.ViewPagerAdapter#createView(java.lang.Object, int)
	 */
	@Override
	public View createView(QuestionVO question, int position) {
		RelativeLayout topicCell = (RelativeLayout) mInflater.inflate(R.layout.question_cell, null);
		ScrollView questionScroll = (ScrollView) topicCell.findViewById(R.id.question_scroll);
		TextView index = (TextView)topicCell.findViewById(R.id.topic_index);
		TextView content = (TextView)topicCell.findViewById(R.id.topic_content);
		LinearLayout answerLayout = (LinearLayout)topicCell.findViewById(R.id.topic_answer_layout);
		TextView solutionTitle = (TextView)topicCell.findViewById(R.id.topic_answer_solution_title);
		TextView solutionContent = (TextView)topicCell.findViewById(R.id.solution_content);
		// 题号
		index.setText(String.format(AppSetting.TOPIC_INDEX, position + 1, getCount()));
		// 题干
		content.setText(question.getQuestionTitle());
		// 创建选项
		try {
			createAnswerGroup(questionScroll, topicCell, answerLayout, question, solutionTitle, solutionContent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return topicCell;
	}
	
	/**
	 * 创建答案组
	 * @param questionScroll 
	 * @param topicCell 
	 * @param answerLayout
	 * @param topicEntity
	 * @param solutionContentView 
	 * @param solutionTitle 
	 */
	private void createAnswerGroup(final ScrollView questionScroll, final RelativeLayout questionCell, LinearLayout answerLayout,final QuestionVO question, final TextView solutionTitle, final TextView solutionContentView){
		final List<QuestionOptionVO> optionList = question.getQuestionOptions();
		final int answerSize = optionList.size();
		// 临时保存选项图片
		final ImageView[] tempIconArray = new ImageView[answerSize];
		final RelativeLayout[] tempIconLayout = new RelativeLayout[answerSize];
		
		// 绘制每个选项
		for (int i=0; i< optionList.size(); i++) {
			final QuestionOptionVO questionOption = optionList.get(i);
			RelativeLayout cellLayout = (RelativeLayout) mInflater.inflate(R.layout.option_selection_cell, null);
			tempIconLayout[i] = (RelativeLayout) cellLayout.findViewById(R.id.answer_icon_layout);
			// 选项图片ABCDE背景
			int bgRes = questionOption.isChecked() ? R.drawable.answer_icon_select_background : R.drawable.answer_icon_background;
			tempIconLayout[i].setBackgroundResource(bgRes);
			
			// 选项图片ABCDE
			final ImageView icon = (ImageView)cellLayout.findViewById(R.id.answer_icon);
			tempIconArray[i] = icon;
			icon.setImageResource(AppSetting.AnswerIcons.SingleChoice.PRESSED[i]);
			
			// 选项内容
			TextView content = (TextView)cellLayout.findViewById(R.id.answer_content);
			content.setText(questionOption.getOptionContent());
			// 添加选项
			answerLayout.addView(cellLayout);
			
			// 已经结束
			if (question.isFinish()) {
				if (questionOption.isCorrect()) {
					tempIconLayout[i].setBackgroundResource(R.drawable.answer_correct_background);
				}
				// 需要显示解决方案
				if (showSolution) {
					if (question.getQuestionSolutions()!=null && question.getQuestionSolutions().size() > 0) {
						String solutionContent = question.getQuestionSolutions().get(0).getSolutionContent();
						solutionTitle.setVisibility(View.VISIBLE);
						solutionContentView.setVisibility(View.VISIBLE);
						solutionContentView.setText(solutionContent);
					}
				}
				continue;
			}
			
			// 记录当前option序号
			final int index = i;
			// 添加点击事件
			cellLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (question.isFinish()) {
						return;
					}
					// 临时记录选中状态
					boolean optionChecked = !questionOption.isChecked();
					// 取消选中其他项
					for(int j=0;j<answerSize;j++){
						QuestionOptionVO otherOption = optionList.get(j);
						otherOption.setChecked(false);
						tempIconLayout[j].setBackgroundResource(R.drawable.answer_icon_background);
						if (otherOption.isCorrect()) {
							tempIconLayout[j].setBackgroundResource(R.drawable.answer_correct_background);
						}
					}
					// 修改选中状态
					questionOption.setChecked(optionChecked);
					if (!questionOption.isCorrect()) {
						int bgRes = optionChecked ? R.drawable.answer_icon_select_background : R.drawable.answer_icon_background;
						tempIconLayout[index].setBackgroundResource(bgRes);
					}
					
					// 需要显示解决方案
					if (showSolution) {
						if (question.getQuestionSolutions()!=null && question.getQuestionSolutions().size() > 0) {
							String solutionContent = question.getQuestionSolutions().get(0).getSolutionContent();
							solutionTitle.setVisibility(View.VISIBLE);
							solutionContentView.setVisibility(View.VISIBLE);
							solutionContentView.setText(solutionContent);
						}
						// 选中了正确答案
						if (optionChecked && questionOption.isCorrect()) {
							question.setCorrect(true);
							Message msg = Message.obtain(mHandler, PracticeHandler.ANSWER_CORRECT);
							msg.obj = question;
							mHandler.sendMessage(msg);
						}
						else {
							Map<String, Object> messageMap = new HashMap<String, Object>();
							messageMap.put("question", question);
							messageMap.put("faultOptionID", questionOption.getId());
							Message msg = Message.obtain(mHandler, PracticeHandler.ANSWER_FAULT);
							msg.obj = messageMap;
							mHandler.sendMessage(msg);
						}
						sendScroll(questionScroll);
					}
					question.setFinish(true);
				}
			});
		}
	}

	private void sendScroll(final ScrollView scrollView){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {Thread.sleep(100);} catch (InterruptedException e) {}
                handler.post(new Runnable() {
                    @Override
                    public void run() {
						scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
        }).start();
    }
	
	private void drawOptions(ImageView[] tempIconArray,
			RelativeLayout[] tempIconLayout) {
		// TODO Auto-generated method stub
		
	}



	/* (non-Javadoc)
	 * @see com.lurencun.android.support.v2.widget.ViewPagerAdapter#finishedUpdate(com.lurencun.android.support.v2.widget.ViewPager)
	 */
	@Override
	protected void finishedUpdate(ViewPager container) {
		
	}
	
	/* (non-Javadoc)
	 * @see com.lurencun.android.support.v2.widget.ViewPagerAdapter#startingUpdate(com.lurencun.android.support.v2.widget.ViewPager)
	 */
	@Override
	protected void startingUpdate(ViewPager container) {
		// TODO Auto-generated method stub
		
	}

	public void setHandler(PracticeHandler handler) {
		this.mHandler = handler;
	}

}
